package com.example.administrator.zjyapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.administrator.zjyapp.SQLiteDatabase.AdDatabaseManager;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button genxinBtn, chaxunBtn,shanchuBtn;
    EditText nameEdit, typeEdit, priceEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        nameEdit = (EditText) this.findViewById(R.id.name);
        typeEdit = (EditText) this.findViewById(R.id.type);
        priceEdit = (EditText) this.findViewById(R.id.price);

        genxinBtn = (Button) this.findViewById(R.id.gengxinBtn);
        chaxunBtn = (Button) this.findViewById(R.id.chaxunBtn);

        genxinBtn.setOnClickListener(this);
        chaxunBtn.setOnClickListener(this);
        //初始化 数据库
        AdDatabaseManager.getInstance().initDatabase();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.chaxunBtn) {
            //读取数据库
            String name = nameEdit.getText().toString();
            if (StringUtil.isEmpty(name)) {
                Toast.makeText(MainActivity.this, "要查找的书名为空,请输入书名后再查找!", Toast.LENGTH_SHORT).show();
                return;
            }
            Book book = AdDatabaseManager.getInstance().getData(nameEdit.getText().toString());
            if (book != null) {
                priceEdit.setText((int) book.getPrice());
                typeEdit.setText(book.getBookType());
                Toast.makeText(MainActivity.this, "读取数据库成功 !", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "读取数据库成功! 未查找到相关数据", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.button) {
            //保存数据库
            String name = nameEdit.getText().toString();
            String author = typeEdit.getText().toString();
            String aaa = String.format("%.2f",priceEdit.getText().toString());//转化String类型，保留两位
            double price = Double.parseDouble(aaa);//转化double

            Book book = new Book();
            book.setBookName(name);
            book.setBookType(author);
            book.setPrice(price);
            AdDatabaseManager.getInstance().insertData(book);
            Toast.makeText(MainActivity.this, "写入成功 !", Toast.LENGTH_SHORT).show();
        }
    }

}
